package org.hxzon.configdesigner.web.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;

public class WebUtil {

    public static final int cookieTime = 3600 * 24 * 14;
    public static final String cookieName_Username = "username";
    public static final String cookieName_LoginToken = "loginToken";

    // file:/d:/xxx
    //myapp/WEB-INF/classes
    private static String webappPath_;
    private static String savePath_;

    public static void init(String webappPath, String savePath) {
        webappPath_ = webappPath;
        savePath_ = savePath;
    }

    public static Cookie addCookie(String name, String value, String path) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath(path);
        cookie.setMaxAge(cookieTime);
        return cookie;
    }

    public static Cookie addCookie(String name, String value) {
        return addCookie(name, value, "/");
    }

    public static Cookie addUsernameCookie(String value) {
        return addCookie(cookieName_Username, value);
    }

    public static Cookie addLoginTokenCookie(String value) {
        return addCookie(cookieName_LoginToken, value);
    }

    protected static String generateFileName(String fileName) {
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
        String formatDate = format.format(new Date());

        int position = fileName.lastIndexOf(".");
        String extension = fileName.substring(position);
        return fileName + formatDate + extension;
    }

    public static String getWebappPath() {
        return webappPath_;
    }

    public static String getWebappPath(String sub) {
        return webappPath_ + sub;
    }

    public static String getSavePath() {
        return savePath_;
    }

    public static String getSavePath(String sub) {
        return savePath_ + sub;
    }
}
